﻿using OznerOA.Model;
using OznerOA.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;


namespace OznerOA.BLL
{
    public class LogBLL
    {
        private static ConcurrentQueue<Log> Logs = new ConcurrentQueue<Log>();
        private string ClassName;
        private string FormText;
        public LogBLL(string className,string formText)
        {
            ClassName = className;
            this.FormText = formText;
        }
        public void Info(string message,params object[] ps)
        {
            AddLog(LogType.INFO, message,ps);
        }
        public void Warn(string message, params object[] ps)
        {
            AddLog(LogType.WARN, message,ps);
        }
        public void Error(string message, params object[] ps)
        {
            AddLog(LogType.ERROR, message,ps);
        }
        public void Debug(string message, params object[] ps)
        {
            AddLog(LogType.DEBUG, message,ps);
        }
        public void WriteFile(Log log)
        {
            string directory = System.IO.Directory.GetCurrentDirectory() + "/logs/";
            string path = directory + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            if (!File.Exists(path))
            {
                File.Create(path).Close();
            }
            FileOperateHelper.FileAdd(path,
                string.Format("[{0}][{1}][{2}]:{3}\r\n", log.DateTime.ToString("yyyy-MM-dd hh:mm:ss"), log.ClassName, log.LogType.ToString(), log.Message));
        }

        private void AddLog(LogType type,string message, params object[] ps)
        {
            Logs.Enqueue(new Log()
            {
                ClassName = this.ClassName,
                Message = message == null?"null":string.Format(message,ps),
                DateTime = DateTime.Now,
                LogType = type,
                FormText = FormText
            });
        }
        /// <summary>
        /// 获取一个出队列并删除
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public bool Dequeue(out Log log)
        {
            return Logs.TryDequeue(out log);
        }

        /// <summary>
        /// 获取一个出队列不删除
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public bool Peek(out Log log)
        {
            return Logs.TryPeek(out log);
        }
        
    }
}
